﻿using System;
using System.Windows;
using System.Windows.Input;
using FirstFloor.ModernUI.Windows.Controls;
using YanMsg.View;
using YanMsg.APCode;
using System.Windows.Media.Animation;
using System.Collections;
using System.Threading.Tasks;
using FirstFloor.ModernUI.Presentation;
using System.IO;
using System.Windows.Controls;
using System.Timers;
using System.Windows.Threading;
using Newtonsoft.Json.Linq;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Threading;

namespace YanMsg
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : ModernWindow
    {
        public DispatcherTimer TimeAutoLJ = new DispatcherTimer();//处理断线重连的计时器

        /// <summary>
        /// 系统定时器
        /// </summary>
        public MainWindow()
        {
            try
            {
                UserData.MainWindow = this;

                new ConfigManger().initData();
                InitializeComponent();
                this.Style = (Style)App.Current.Resources["EmptyWindow"];
                this.Focus();
                TBAppVersion.Text = "YanChat " + ConfigManger.CurrentVersion;
                UserData.MainWindow.Wait();
                Task task = new Task(TaskMethod);
                task.Start();

                NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkCallback);

                //处理断线重连
                TimeAutoLJ.Interval = new TimeSpan(0, 0, 5);
                TimeAutoLJ.Stop();
                TimeAutoLJ.Tick += new EventHandler(ReConnect);
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message + "1");
            }


        }
        void ReConnect(object sender, EventArgs e)
        {
            try
            {
                if (ConfigManger.ServerAutoLogin == "Y")
                {
                    if (new ChatHelp().Ping(ConfigManger.ServerIP))
                    {
                        this.Dispatcher.Invoke(new Action(() =>
                        {
                            Thread.Sleep(new TimeSpan(0, 0, 2));
                            if (Application_Init.GetIconUserState() == "3")//离线状态
                            {
                                UserData.MainWindow.ReturnPage(new Login(ConfigManger.ClientUserName, ConfigManger.ClientPassword, "Y"));
                            }
                        }));
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message + "1");
            }
        }

        private void NetworkCallback(object sender, EventArgs e)
        {
            if (ConfigManger.ServerAutoLogin == "Y")
            {
                if (!new ChatHelp().Ping(ConfigManger.ServerIP))
                {
                    if (Application_Init.GetIconUserState() == "0")//在线状态
                    {
                        this.Dispatcher.Invoke(new Action(() =>
                        {
                            UserData.MainWindow.ReturnPage(new Login(ConfigManger.ClientUserName, ConfigManger.ClientPassword, ""));
                            Application_Init.notifyIconUserState(3);
                            UserData.MainWindow.TimeAutoLJ.Start();
                        }));
                    }
                }
            }
        }
        private void TaskMethod()
        {
            Ezhu.AutoUpdater.Updater.CheckUpdateStatus(ConfigManger.ClientUpdatePath);
            Dispatcher.BeginInvoke(new Action(delegate()
            {
                Application_Init.Initial();
                try
                {
                    string strUserSkin = ConfigManger.ClientUserSkin;
                    if (strUserSkin.Trim() != "")
                    {
                        string strColorIndex = strUserSkin.Split('@')[0] ?? "2";
                        string strSkin = strUserSkin.Split('@')[1] ?? "ModernUI.Light.xaml";
                        AppearanceManager.Current.AccentColor = (new SettingsAppearanceViewModel().AccentColors)[int.Parse(strColorIndex)];
                        AppearanceManager.Current.ThemeSource = new System.Uri("/YanMsg;component/Assets/" + strUserSkin.Split('@')[1].ToString(), UriKind.Relative);
                    }
                    AddPage(new Login(ConfigManger.ClientUserName, ConfigManger.ClientPassword, ConfigManger.ClientisAutoRun));

                    //设置开机自启动
                    if (ConfigManger.ClientisStartUp == "Y")
                    {
                        new ConfigManger().SetAutoRun("YanChat", Process.GetCurrentProcess().MainModule.FileName);
                    }
                }
                catch (Exception)
                {
                    MsgManger.ShowTip("程序出错了,联系管理员吧");
                }
            }), null);
        }

        public void AddPage(UIElement Page)
        {
            MainContent.Children.Clear();
            UserData.MainWindow.MainContent.Children.Add(Page);

            Storyboard s = new Storyboard();
            this.Resources.Add(Guid.NewGuid().ToString(), s);
            DoubleAnimation da = new DoubleAnimation();
            Storyboard.SetTarget(da, Page);
            Storyboard.SetTargetProperty(da, new PropertyPath("Opacity", new object[] { }));
            da.From = 0;
            da.To = 1;
            s.Duration = new Duration(TimeSpan.FromSeconds(1));
            s.Children.Add(da);
            s.Begin();
        }

        public void ReturnPage(UIElement Page)
        {
            MainContent.Children.Clear();
            UserData.MainWindow.MainContent.Children.Add(Page);

        }

        public void Wait()
        {
            MainContent.Children.Clear();
            UserData.MainWindow.MainContent.Children.Add(new ProGressBarPage());
        }






        private void MainWindow_Closed(object sender, EventArgs e)
        {
            if (Login.connection != null && Login.connection.Username != "")
            {
                Login.connection.Close();
            }
            UserData.notifyIcon.Dispose();

        }

        /// <summary>
        /// 关闭前动作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (UserData.notifyIcon.Icon == UserData.Icon_Online)
            {
                e.Cancel = true;
                this.Hide();
            }
            else
            {
                var result = ModernDialog.ShowMessage("是否要退出YanMsg", "提示", MessageBoxButton.YesNo);
                //关闭窗口
                if (result.ToString() == "Yes")
                {
                    e.Cancel = false;
                }
                else
                {
                    e.Cancel = true;
                }
            }




        }

        private void ModernWindow_StateChanged(object sender, EventArgs e)
        {
            if (this.WindowState == System.Windows.WindowState.Minimized)
            {
                this.Hide();
            }
        }


        private void File_PreviewDragEnter(object sender, DragEventArgs e)
        {
            AppearanceManager.Current.ThemeSource = new System.Uri("/YanMsg;component/Assets/ModernUI.Light.xaml", UriKind.Relative);
            e.Effects = DragDropEffects.Copy;
            e.Handled = true;
        }

        private void File_PreviewDrop(object sender, DragEventArgs e)
        {
            Array arr = (Array)e.Data.GetData(DataFormats.FileDrop);
            if (arr != null)
            {
                try
                {
                    foreach (var sendfile in arr)
                    {

                        string sourceFile = sendfile.ToString();
                        if (sourceFile.Substring(sourceFile.ToString().LastIndexOf(".") + 1) != "jpg")
                        {
                            MsgManger.Show("必须是Jpg文件哦！");
                        }
                        else
                        {
                            BingImage.strBGName = sourceFile.Substring(sourceFile.ToString().LastIndexOf("\\") + 1);
                            string destinationFile = UserData.MySkin + BingImage.strBGName;
                            if (File.Exists(sourceFile))
                            {
                                // true is overwrite 
                                File.Copy(sourceFile, destinationFile, true);
                            }
                            AppearanceManager.Current.ThemeSource = new System.Uri("/YanMsg;component/Assets/ModernUI.BingImage.xaml", UriKind.Relative);
                            new ConfigManger().SetConfig("ClientUserBG", BingImage.strBGName);
                        }


                    }
                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show(ex.Message);
                }
            }
        }






        #region//设置菜单




        private void btnMenu_Initialized(object sender, EventArgs e)
        {
            //设置右键菜单为null
            this.imgSysSet.ContextMenu = null;
        }
        /// <summary>
        /// 改变样式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void imgSysSet_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //目标
            this.contextMenu.PlacementTarget = this.imgSysSet;
            //显示菜单
            this.contextMenu.IsOpen = true;

        }

        /// <summary>
        /// 设置主题
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MnuSetSkin_Click(object sender, RoutedEventArgs e)
        {
            new ModernDialog
            {
                Title = "主题设置",
                Content = new SettingsAppearance { Width = 500, Height = 300 }
            }.Show();
        }

        //检查更新
        private void MnuCheckUpdate_Click(object sender, RoutedEventArgs e)
        {
            Ezhu.AutoUpdater.Updater.CheckUpdateStatus(ConfigManger.ClientUpdatePath);
        }


        #endregion
        //消息中心
        private void btXXZX_Click(object sender, RoutedEventArgs e)
        {
            MsgManger.ShowWindows(new MsgBox());
        }
        private void Main_Loaded(object sender, RoutedEventArgs e)
        {
            this.MouseEnter += delegate(Object o, MouseEventArgs me)
            {
                if (this.Top < 0)
                {
                    Storyboard s = new Storyboard();
                    DoubleAnimationUsingKeyFrames d = new DoubleAnimationUsingKeyFrames();
                    d.KeyFrames.Add(new LinearDoubleKeyFrame(0, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0.2))));
                    s.Children.Add(d);
                    Storyboard.SetTargetName(d, this.Name);
                    Storyboard.SetTargetProperty(d, new PropertyPath(Canvas.TopProperty));
                    s.Begin(this);
                }
            };

            this.MouseLeave += delegate(Object o, MouseEventArgs me)
            {
                if (this.RestoreBounds.Top == 0)
                {
                    Storyboard s = new Storyboard();
                    DoubleAnimationUsingKeyFrames d = new DoubleAnimationUsingKeyFrames();
                    d.KeyFrames.Add(new LinearDoubleKeyFrame(10 - this.ActualHeight, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0.2))));
                    s.Children.Add(d);
                    Storyboard.SetTargetName(d, this.Name);
                    Storyboard.SetTargetProperty(d, new PropertyPath(Canvas.TopProperty));
                    s.Begin(this);


                }
            };
        }


        //添加日志
        private void MenuAddLog_Click(object sender, RoutedEventArgs e)
        {
            new AddDayLog().Show();
        }

        private void imgFileCenter_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            new FileTable().Show();
        }


        //系统设置
        private void btSysSet_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(UserData.UserNumber))
            {
                new sysset(UserData.UserNumber).Show();
            }
            else
            {
                MsgManger.Show("请先登录");
            }
        }

        private void MnuLogout_Click(object sender, RoutedEventArgs e)
        {
            new ConfigManger().DelConfig("ClientUserName");
            new ConfigManger().DelConfig("ClientPassword");
            new ConfigManger().DelConfig("ClientisAutoRun");
        }

        private void MnuExit_Click(object sender, RoutedEventArgs e)
        {
            Application_Init.Exit();
        }
    }
}
